import { formatDate,getDiff } from '@/utils/moment/index.js';
export const useEnvelope = {
	methods: {
		// 查询优惠券详情
		getCouponInfo (couponId) {
			return new Promise((resolve,reject)=>{
				this.$resPost('GetCouponInfo', { pk_id: couponId }).then(({ data }) => {
					if (data && data.pk_id) {
						let couponForm = {
							...data
						};
						// if(couponForm.coupon_receive_use){
						// 	// 已使用
						// }else 
						if(couponForm.coupon_receive_status == 1){
							// 已领取
							let end = new Date(couponForm.coupon_receive_effective);
							let start = new Date();
							if (end.getTime() <= start.getTime()) {
								couponForm.nearly = 2; // 1.即将过期  2已过期
							} else {
								let day = getDiff(start, end);
								couponForm.nearly = day > 1 ? 0 : 1;
							}
						}else{
							// 未领取
							let end = new Date(couponForm.end_effective);
							let start = new Date();
							if (end.getTime() <= start.getTime()) {
								couponForm.nearly = 2; // 1.即将过期  2已过期
							} else {
								let day = getDiff(start, end);
								couponForm.nearly = day > 1 ? 0 : 1;
							}
						}
						resolve(couponForm)
					}else{
						reject()
					}
				}).catch(()=>{reject()})
			})
		},
		// 领取兑换优惠券红包
		receiveCoupon(couponForm,receive_id,num=1) {
			if(couponForm.nearly == 2){
				this.$toast('优惠券已过期')
				return
			}else if(couponForm.coupon_receive_status == 1){
				this.$toast('已领取过该优惠券')
				return
			}
			this.$loading();
			let day = couponForm.effective || 1;
			let date = new Date();
			date.setDate(date.getDate() + day);
			date = formatDate(date, 'YYYY-MM-DD HH:mm:ss');
			this.$resPost('AddCouponReceive', {
				coupon_id: couponForm.pk_id,
				date_effective: date
			}).then(() => {
				this.useSuccessEnvelop(2,'',receive_id,num,'领取成功')
			});
		},
		// 积分充值
		receiveIntegral (integral,num,receive_id) {
			if(num <= 0){
				this.$toast('红包数量不足')
				return
			}
			uni.showModal({
				title: `兑换${num}个红包`,
				content: `确定充值${integral}积分？`,
				success: res => {
					if (res.confirm) {
						this.$resPost('AddUsersIntegral', {
							remark: `红包${receive_id}兑换`,
							type: 3,
							integral
						}).then(()=>{
							this.useSuccessEnvelop(3,'',receive_id,num,'积分充值成功')
						})
					}
				}
			});
		},
		useSuccessEnvelop(type, order_no,receive_id,num=1,successMsg="使用成功") {
			let typeObj = {
				2: '优惠券兑换',
				3: '积分充值',
				4: '余额充值'
			}
			let msg = typeObj[type]
			// 使用掉红包
			this.$resPost('AddUsersRedRecord', {
				receive_id: receive_id,
				mode: 1,
				num: num,
				title: msg,
				order_no: order_no,
				relay_num: 0
			}).then(()=>{
				this.$toast(successMsg)
				this.pageInit()
			})
		}
	}
}
